package com.lwf.fatapi.mapper;

import com.lwf.fatapi.entities.OrganizationUnit;
import com.mybatisflex.core.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 组织单元 Mapper 接口
 *
 * @author lwf
 */
@Mapper
public interface OrganizationUnitMapper extends BaseMapper<OrganizationUnit> {

    /**
     * 根据项目ID查询所有组织单元
     */
    @Select("SELECT * FROM organization_unit WHERE project_id = #{projectId} AND is_deleted = 0 ORDER BY level_num, sort_order")
    List<OrganizationUnit> selectByProjectId(@Param("projectId") Long projectId);

    /**
     * 根据父级ID查询子组织单元
     */
    @Select("SELECT * FROM organization_unit WHERE parent_id = #{parentId} AND is_deleted = 0 ORDER BY sort_order")
    List<OrganizationUnit> selectByParentId(@Param("parentId") Long parentId);

    /**
     * 检查单元编码在项目内是否唯一
     */
    @Select("SELECT COUNT(*) FROM organization_unit WHERE project_id = #{projectId} AND unit_code = #{unitCode} AND is_deleted = 0 AND id != #{excludeId}")
    int countByProjectIdAndUnitCode(@Param("projectId") Long projectId, @Param("unitCode") String unitCode, @Param("excludeId") Long excludeId);

    /**
     * 查询指定单元的所有子单元ID（递归）
     */
    @Select("WITH RECURSIVE unit_tree AS (" +
            "  SELECT id FROM organization_unit WHERE parent_id = #{parentId} AND is_deleted = 0" +
            "  UNION ALL" +
            "  SELECT ou.id FROM organization_unit ou " +
            "  INNER JOIN unit_tree ut ON ou.parent_id = ut.id " +
            "  WHERE ou.is_deleted = 0" +
            ") SELECT id FROM unit_tree")
    List<Long> selectChildUnitIds(@Param("parentId") Long parentId);

    /**
     * 更新单元的层级数
     */
    @Select("UPDATE organization_unit SET level_num = #{levelNum}, update_time = CURRENT_TIMESTAMP WHERE id = #{id}")
    void updateLevelNum(@Param("id") Long id, @Param("levelNum") Integer levelNum);
}
